package com.cqie.rbac.handler;

import com.cqie.rbac.exception.BusinessException;
import com.cqie.rbac.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 夏兵
 * @Date 2021/9/6
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("服务错误: " + e.getMessage());
        log.error("请求地址: " + request.getRequestURL());
        e.printStackTrace();
        return Result.unknowServerError();
    }

    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest request, BusinessException e) {
        log.error("业务错误----> code: " + e.getCode() + ", Message: " + e.getMsg());
        log.error("请求地址: " + request.getRequestURL());
        e.printStackTrace();
        return Result.error().code(e.getCode()).message(e.getMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    public Result nullPointerException(HttpServletRequest request, Exception e) {
        log.error("服务错误: " + e.getMessage());
        log.error("请求地址: " + request.getRequestURL());
        e.printStackTrace();
        return Result.error().message("空指针");
    }

    @ExceptionHandler(value = UnauthorizedException.class)
    public Result unauthorizedException(HttpServletRequest request, Exception e) {
        log.error("业务错误: " + e.getMessage());
        log.error("请求地址: " + request.getRequestURL());
        e.printStackTrace();
        return Result.error().message("你没有该权限");
    }
}
